package com.example.common.utils;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

public class SecurityUtil {
    
    /**
     * 获取当前认证对象；如果不存在则返回 null
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
    
    /**
     * 清除当前的认证信息
     */
    public static void clearAuthentication() {
        SecurityContextHolder.clearContext();
    }
    
    /**
     * 获取当前认证的Web认证详情；如果不存在则返回 null
     */
    public static WebAuthenticationDetails getWebAuthenticationDetails() {
        Authentication auth = getAuthentication();
        if (auth != null && auth.getDetails() instanceof WebAuthenticationDetails) {
            return (WebAuthenticationDetails) auth.getDetails();
        }
        return null;
    }
    
    /**
     * 获取当前登录用户的用户名，如果未认证则返回 null
     */
    public static String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        } else if (principal instanceof String) {
            return (String) principal;
        }
        return null;
    }
    
    
    /**
     * 判断当前用户是否拥有指定角色
     * @param role 角色名称（不带 "ROLE_" 前缀）
     */
    public static boolean hasRole(String role) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return false;
        }
        return authentication.getAuthorities().stream()
                   .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ROLE_" + role));
    }
    
    
}
